import axios from "axios";
import { ElMessage } from "element-plus";
import { useUserStore } from "../store/modules/user";
const instance = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 8000
})
// 请求拦截

instance.interceptors.request.use(config => {
    const {token} = useUserStore()
    if (token) {
        config.headers.token = token
    }
    return config
}, err => Promise.reject(err))

// 响应拦截
instance.interceptors.response.use(res => {
    return res.data
}, err => {
    let message = '';
    const status = err.response.status
    if (status === 401) {
        message = 'token过期'
    } else if (status === 403) {
        message = '无权访问'
    } else if (status === 404) {
        message = '请求地址错误'
    } else if (status === 500) {
        message = '服务器出现问题'
    }
    ElMessage({
        type: 'error',
        message
    })
    return Promise.reject(err)
})

export default instance